package com.demo.supplier.controller;

import com.demo.supplier.common.R;
import com.demo.supplier.constant.ApiConstants;
import com.demo.supplier.exception.BusinessException;
import com.demo.supplier.service.FileService;
import com.demo.supplier.vo.FileInfoVo;
import com.demo.supplier.vo.FileUploadVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 文件管理控制器
 * 
 * @author demo
 */
@Slf4j
@RestController
@RequestMapping("${api.prefix}" + ApiConstants.FILES)
@Api(tags = "文件管理")
public class FileController {

    @Autowired
    private FileService fileService;

    @PostMapping("/upload")
    @ApiOperation("单文件上传")
    public R<FileUploadVo> uploadFile(@ApiParam("上传文件") @RequestParam("file") MultipartFile file) {
        FileUploadVo result = fileService.uploadFileWithDb(file);
        return R.success("文件上传成功", result);
    }

    @PostMapping("/upload/batch")
    @ApiOperation("批量文件上传")
    public R<List<FileUploadVo>> uploadFiles(@ApiParam("上传文件列表") @RequestParam("files") List<MultipartFile> files) {
        List<FileUploadVo> result = fileService.uploadFiles(files);
        return R.success("批量上传成功", result);
    }

    @GetMapping("/{fileId}")
    @ApiOperation("获取文件信息")
    public R<FileInfoVo> getFileInfo(@ApiParam("文件ID") @PathVariable Long fileId) {
        FileInfoVo result = fileService.getFileInfo(fileId);
        return R.success("获取成功", result);
    }

    @GetMapping("/{fileId}/url")
    @ApiOperation("获取文件访问URL")
    public R<String> getFileUrl(@ApiParam("文件ID") @PathVariable Long fileId) {
        String url = fileService.getFileUrlById(fileId);
        return R.success("获取成功", url);
    }

    @DeleteMapping("/{fileId}")
    @ApiOperation("删除文件")
    public R<String> deleteFile(@ApiParam("文件ID") @PathVariable Long fileId) {
        // 检查文件是否被使用
        if (fileService.isFileInUse(fileId)) {
            throw new BusinessException("文件正在被使用，无法删除");
        }
        fileService.deleteFileById(fileId);
        return R.success("删除成功");
    }
}